package com.pgcomb.poweriot.alarmservice.alarm.service;

import com.pgcomb.web.dao.DataId;
import com.pgcomb.web.repo.DataIdRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * Title: KeyService <br>
 * Description: KeyService <br>
 * Date: 2021年05月29日
 *
 * @author lirong
 * @version 1.0.0
 * @since jdk8
 */
@Service
public class KeyService {
    /**
     * 警告规则
     */
    public static final String ALARM_RULE_KEY = "alarm_rule_key";

    /**
     * 告警记录
     */
    public static final String ALARM_MSG_KEY = "alarm_msg_KEY";

    @Autowired
    private DataIdRepo dataIdRepo;

    public void init() {
        synchronized (KeyService.class) {
            save(ALARM_RULE_KEY);
            save(ALARM_MSG_KEY);
        }
    }

    private DataId save(String key) {
        DataId id = dataIdRepo.findByKey(key);
        if (id == null) {
            //初始化0
            id = dataIdRepo.save(new DataId(key, 0));
        }
        return id;
    }

    public Integer alarmRule() {
        synchronized (KeyService.class) {
            DataId byKey = dataIdRepo.findByKey(ALARM_RULE_KEY);
            byKey.setValue(byKey.getValue() + 1);
            dataIdRepo.save(byKey);
            return byKey.getValue();
        }

    }

    public Integer alarmMsg() {
        synchronized (KeyService.class) {
            DataId byKey = dataIdRepo.findByKey(ALARM_MSG_KEY);
            if(ObjectUtils.isEmpty(byKey)){
                byKey = save(ALARM_MSG_KEY);
            }
            byKey.setValue(byKey.getValue() + 1);
            dataIdRepo.save(byKey);
            return byKey.getValue();
        }
    }


    public String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        StringBuffer sb = null;
        while (strLen < strLength) {
            sb = new StringBuffer();
            sb.append("0").append(str);
            str = sb.toString();
            strLen = str.length();
        }
        return str.toUpperCase();
    }


}
